<template>
    <div class="progress">
        <div class="bar" ref="bar">
        </div>
    </div>
</template>

<script>
import { fetchEventSource } from '@microsoft/fetch-event-source';

export default {
    props: {
    },
    mounted(){
        
    },
    methods: {
        start(arg){
            let {url, param} = arg;
            let that = this;
            fetchEventSource(url, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(param),
                onmessage(event) {
                    that.$refs.bar.style.width = event.data+'%';
                },
                onopen(response) {   
                    if (response.ok && response.headers.get('content-type').indexOf('text/event-stream')>=0) {
                        console.log('创建长连接成功！');
                        return;
                    }
                    throw new Error(`Failed to open connection: ${response.status} ${response.statusText}`);
                },
                onclose() {
                    console.log('Event source closed');
                },
                onerror(error) {
                    console.log(error);
                    console.error('Event source failed AAA:', error);
                    // 这里可以添加重试逻辑
                    throw error;
                },
            });
        }
    }
}
///JAVA 中创建SSE的DEMO
// @RestController
// @RequestMapping("/test/")
// @CrossOrigin(origins = "*", methods = {RequestMethod.POST})
// public class TestController {

//     @ResponseBody
//     @PostMapping(value="events",produces = "text/event-stream")
//     void getEventSource(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
//         System.out.println("getDate event start");
//         response.setContentType("text/event-stream");
//         response.setCharacterEncoding("UTF-8");
//         response.setStatus(200);
//         for (int i = 0; i < 100; i++) {
//             String msg="data:" + (i+1) + "\n\n";
//             response.getWriter().write(msg);
//             System.out.println(msg);
//             response.getWriter().flush();
//             Thread.sleep(500);
//         }
//         response.getWriter().close();
//         System.out.println("getDate event end");
//     }
// }
///
</script>

<style scoped>
.progress{
    width: 100%;    
    background-color: rgb(208, 208, 208);
    display: block;
    min-height: 20px;
}
.bar{
    height: 100%;
    min-height: 20px;
    background-color: var(--theme-primary-color);
    display: block;
    width: 0%;
}
</style>